package sp

import (
	"gin-sso/jwtx"
	"github.com/gin-gonic/gin"
	"net/http"
)

var idpLoginURL = "http://localhost:8080/loginHTML" // IdP的登录地址

func CallbackHandler(c *gin.Context) {
	//fmt.Println("Request:", c.Request.URL.String())
	tokenString := c.Query("token")
	if tokenString == "" {
		c.String(http.StatusBadRequest, "令牌不存在")
		return
	}

	// 验证JWT
	_, err := jwtx.VerifyToken(tokenString)
	if err != nil {
		c.String(http.StatusUnauthorized, "令牌验证失败: "+err.Error())
		return
	}

	// 验证通过，将JWT存入Cookie（设置HttpOnly防止XSS）
	c.SetCookie(
		"sso_token",
		tokenString,
		7200, // 2小时过期（与JWT过期时间一致）
		"/",  // 所有路径可见
		"localhost",
		false, // 开发环境不启用HTTPS
		true,  // HttpOnly
	)

	// 跳回用户最初请求的页面
	redirectURL := c.Query("redirect")
	if redirectURL == "" {
		redirectURL = "/user"
	}
	c.Redirect(http.StatusFound, redirectURL)
}

func UserHandler(c *gin.Context) {
	userID, _ := c.Get("userID")
	username, _ := c.Get("username")
	c.JSON(http.StatusOK, gin.H{
		"message":  "登录成功",
		"user_id":  userID,
		"username": username,
	})
}
